using System;
using System.Xml;
using System.Xml.Xsl;
using System.IO;
using System.Text;
using System.Net;

using ICSharpCode.SharpZipLib;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Zip.Compression;
using ICSharpCode.SharpZipLib.Zip.Compression.Streams;


namespace umbSearch.businessLogic.defaultFilters.helpers
{
	/// <summary>
	/// Summary description for OpenOfficeIndexer.
	/// </summary>
	public class OpenOfficeIndexer
	{
		public OpenOfficeIndexer()
		{
		}

		public static string Parse(string FileToParse) 
		{
			string content = "";

			// Unzip file and grap content.xml
			string contentXml = UnZipAndReturnContentXml(FileToParse);

			// Use xslt to get content
			content = TransformOpenOffice(contentXml + Path.DirectorySeparatorChar + "content.xml");

			// Do file clean-up
			CleanUp(contentXml);

			// return text
			return content;

		}

		private static void CleanUp(string UnZipDir) 
		{
			System.IO.Directory.Delete(UnZipDir, true);			
		}


		private static string TransformOpenOffice(string ContentXml) 
		{
			XslTransform ooXslt = new XslTransform();
			System.IO.TextReader xslTr;
			XmlReader xslReader = null;
			try 
			{
				xslTr = new System.IO.StreamReader(System.Web.HttpContext.Current.Server.MapPath(umbraco.GlobalSettings.StorageDirectory + Path.DirectorySeparatorChar + "umbSearch" + Path.DirectorySeparatorChar + "ParseOpenOffice.xslt"));
				xslReader = new XmlTextReader(xslTr);
				XmlUrlResolver xslResolver = new XmlUrlResolver();
				xslResolver.Credentials = CredentialCache.DefaultCredentials;
				ooXslt.Load(xslReader, xslResolver, null);

				StringBuilder sb=new StringBuilder();
				TextWriter tw=new StringWriter(sb);
				XmlDocument xd = new XmlDocument();
				xd.Load(ContentXml);
				ooXslt.Transform(xd, null, tw, xslResolver);

				xslReader.Close();
				xslTr.Close();

				return sb.ToString();

			} 
			catch (Exception ee) {
				throw new Exception("Error transforming openoffice document '" + ContentXml + "'", ee);
			}

		}

		private static string UnZipAndReturnContentXml(string FullPathToFile) 
		{
			string tempDir = System.Web.HttpContext.Current.Server.MapPath(umbraco.GlobalSettings.StorageDirectory) + Path.DirectorySeparatorChar + Guid.NewGuid().ToString();
			Directory.CreateDirectory(tempDir);

			ZipInputStream s = new ZipInputStream(File.OpenRead(FullPathToFile));
		
			ZipEntry theEntry;
			while ((theEntry = s.GetNextEntry()) != null) 
			{
				string directoryName = Path.GetDirectoryName(theEntry.Name);
				string fileName      = Path.GetFileName(theEntry.Name);

				// Grab the content xml file
				if (fileName.ToLower() == "content.xml") 
				{
					FileStream streamWriter = File.Create(tempDir + Path.DirectorySeparatorChar + fileName);

					int size = 2048;
					byte[] data = new byte[2048];
					while (true) 
					{
						size = s.Read(data, 0, data.Length);
						if (size > 0) 
						{
							streamWriter.Write(data, 0, size);
						} 
						else 
						{
							break;
						}
					}

					streamWriter.Close();

				}
			}

			// Clean up
			s.Close();

			return tempDir;

		}
	}
}
